<?php

/**
 * Terminal Test
 * php .\usdterc20.php getTransactionByHash 0x26352c9a9832696efc6a102c913ec4cca3b6ba7cf9c8a237de9f4a8712cbcace
 * php .\usdterc20.php getTransactionByAddress 0x63c889bf03bc625dc3b9c14bf290003f9db5b423 9941766
 */
$arg1 = $argv[1];
$arg2 = $argv[2];
$arg3 = $argv[3];

switch ($arg1) {
    case "getTransactionByHash":
        $transaction = getTransactionByHash($arg2);
        var_dump($transaction);
    break;
    case "getTransactionByAddress":
        $transaction = getTransactionByAddress($arg2, $arg3);
        var_dump($transaction);
    break;
    default:
        var_dump("nothing to do");
}
        

function getTransactionByHash($hash) {
    require_once('./lib/clienteth.php');
    $ethclient = new EthClient("192.168.1.217", 8545);

    $result = $ethclient->eth_getTransactionByHash($hash);
    $input = $result['input'];
    if (strlen($input) == 138) {
        // $input = '0xa9059cbb00000000000000000000000075e89d5979e4f6fba9f97c104c2f0afb3f1dcb8800000000000000000000000000000000000000000000000000000000040fc944';
        $amount = substr($input, 74, 64);
        $toAddress = "0x" . substr($input, 34, 40);
        if ($result['to'] == '0xdac17f958d2ee523a2206206994597c13d831ec7') {
            $result['amount'] = $amount;
            $result['toAddress'] = $toAddress;
            return $result;
        }
    }
    return false;
}

function getTransactionByAddress($address, $startnumber) {
    require_once('./lib/clienteth.php');
    $ethclient = new EthClient("192.168.1.217", 8545);

    $endnumber = $ethclient->eth_blockNumber(true);
    if ($endnumber == 0) $endnumber = $startnumber + 1;
    $transactionlist = [];

    for ($i = $startnumber; $i <= $endnumber; $i++) {
        // echo "blocknumber: " . $i . "\n";
        $block = $ethclient->eth_getBlockByNumber($ethclient->encode_dec($i), true);
        if ($block['transactions'] != NULL) {
            for ($k = 0; $k < count($block['transactions']); $k++) {
                $transaction = $block['transactions'][$k];
                if (strlen($transaction['input']) == 138) {
                    $amount = substr($transaction['input'], 74, 64);
                    $toAddress = "0x" . substr($transaction['input'], 34, 40);
                    if ($transaction['to'] == '0xdac17f958d2ee523a2206206994597c13d831ec7') {
                        $transaction['amount'] = $amount;
                        $transaction['toAddress'] = $toAddress;
                        
                        $transactionlist[] = $transaction;
                    }
                }
            }
        }
    }

    // echo "\n\n\n";
    return $transactionlist;
}